package cn.ubeta.b2c.update;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;

import cn.ubeta.b2c.R;
import cn.ubeta.b2c.utils.Constants;
import cn.ubeta.b2c.utils.FileUtils;

import java.io.File;

import static android.os.Environment.getExternalStorageDirectory;

/**
 * Created by denny on 16/6/29.
 */

public class DownloadingService extends Service {

    public final static String PARAMS_VERSION = "version";
    public final static String PARAMS_APK_URL = "apk_url";

    private BroadcastReceiver mDownloadReceiver;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int retVal = super.onStartCommand(intent, flags, startId);

        String version = intent.getStringExtra(PARAMS_VERSION);
        String apkUrl = intent.getStringExtra(PARAMS_APK_URL);

        startDownloadApk(version, apkUrl);

        return retVal;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 启动apk下载
     */
    private void startDownloadApk(String version, String apkUrl) {
        String fileName = "jdvr_" + version + ".apk";
        String localFileName = getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_DOWNLOADS  + "/" + fileName;
        File file = new File(localFileName);
        // 检查是否已经下载
        if (file.exists()) {
            //startInstallApk(this, file);
            //return;
            FileUtils.deleteFile(localFileName);
        }
        final DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(apkUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setTitle(getString(R.string.app_name));
        request.setDescription("正在下载...");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType(Constants.MIMETYPE_APK);

        downloadManager.enqueue(request);
        if (mDownloadReceiver == null) {
            mDownloadReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
                        DownloadManager.Query query = new DownloadManager.Query();
                        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                        query.setFilterById(id);
                        Cursor c = manager.query(query);
                        if (c.moveToFirst()) {
                            String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                            if (filename != null){
                                startInstallApk(context, new File(filename));
                                stopSelf();
                            }
                        }
                        c.close();
                    }
                }
            };
            IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            registerReceiver(mDownloadReceiver, filter);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDownloadReceiver != null) {
            // 取消监听
            unregisterReceiver(mDownloadReceiver);
            mDownloadReceiver = null;
        }
    }

    /**
     * 启动安装
     * @param file
     */
    private static void startInstallApk(Context context, File file) {
        Intent apkIntent = new Intent(Intent.ACTION_VIEW);
        apkIntent.setDataAndType(Uri.fromFile(file), Constants.MIMETYPE_APK);
        apkIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(apkIntent);
    }

}
